#include <iostream>
#include <cstdlib>
#include <string>
#include <cstdio>
#include <cstring>
#include <assert.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

int main()
{
   int pipefd[2] = {0};//创建文件描述符数组
   int n = pipe(pipefd);//创建匿名管道
   assert(n != -1);
   pid_t id = fork();
   assert(id != -1);

   if (id == 0) // 子进程进行读
   {

      char buffer[1024 * 8];
      close(pipefd[1]); // 关闭写端
      sleep(8);
      while (true)
      {
         ssize_t s = read(pipefd[0], buffer, sizeof(buffer) - 1);

         if (s == 0) // 读到文件末尾
         {
            cout << "father quit I quit" << endl;
            break;
         }
         else
         {
            cout << "child read a message[" << getpid() << "] father say:" << buffer << endl;
         }
      }
      exit(0);
   }
   else // 父进程进行写
   {
      close(pipefd[0]); // 关闭读端
      string message = "我是父进程，我正在给你发消息";
      int count = 0;
      char send[1024 * 8];
       //sleep(10);
      while (true)
      {
         int n = snprintf(send, sizeof(send) - 1, "%s[%d]  %d", message.c_str(), getpid(), count++);
         write(pipefd[1], send, sizeof(send) - 1);
         sleep(1);
         if (count == 10)
         {
            cout << "writer quit(father)" << endl;
            break;
         }
      }
      close(pipefd[1]);
      int ret = waitpid(id, nullptr, 0);
      assert(ret > 0);
      cout << ret << endl;
      return 0;
   }
}